package com.cyan.app.workflow.activity.WHM;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.activity.SFC.GdlkCkActivity;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.ManpahdTLabBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.DatePickerDialog;
import com.cyan.app.workflow.customview.PullDownView;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by DXW on 2016-03-29.
 */
public class GdllActivity extends BaseActivity  implements PullDownView.OnPullDownListener, AdapterView.OnItemClickListener{
    private TextView mTextView;
    private Button mButton;
    private EditText mEditTextCK;
    private EditText mEditTextUser;
    private EditText mEditTextMannos;
    public static final String WAREH = "gdll_wareh";
    private EditText mEditTextBeginDate;
    private EditText mEditTextEndDate;

    public static final String TAG = "GdllActivity";
    private List<ManpahdTLabBean.ManpahdTBean> manpahdTBeans;
    private SalaryAdapter adapter;
    private ListView prossinfo_lv;
    private PullDownView mPullDownView;
    private Boolean isPressMore = false;
    private int pageCount = 8;
    private Context context = null;
    /** 请求第几页数据 */
    private int intPageNo = 1;
    /** 是否有下一页 */
    private boolean nextPage = false;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private List<ManpahdTLabBean.ManpahdTBean> mSalaryDatas = new ArrayList<ManpahdTLabBean.ManpahdTBean>();
    private int selectedIndex=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whm_gdll);
        titleBar();
        mPullDownView = (PullDownView) findViewById(R.id.whm_gdll_lv);
        mPullDownView.setOnPullDownListener(this);
        prossinfo_lv = mPullDownView.getListView();
        prossinfo_lv.setOnItemClickListener(this);
        // 隐藏并且禁用头部刷新
        mPullDownView.setHideHeader();
    }

        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
        }

        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0001 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("wareh");
                mEditTextCK.setText(String.valueOf(result));
                PreferenceManager.getDefaultSharedPreferences(this).edit().putString(WAREH,result).commit();
            }
        }
        if(requestCode == 0x0002 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("appuser");
                mEditTextUser.setText(String.valueOf(result));
            }
        }
        if(requestCode == 0x0003 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                if(!mEditTextMannos.getText().toString().isEmpty()&& mEditTextMannos.getText().toString().indexOf(result)<0){
                    result = mEditTextMannos.getText().toString() + "," + result;
                }
                mEditTextMannos.setText(String.valueOf(result));
            }
        }
            if(requestCode == 0x0004 && resultCode == RESULT_OK){
                manpahdTBeans.remove(selectedIndex);
                mSalaryDatas.remove(selectedIndex);
                adapter.notifyDataSetChanged();
            }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //adapter.notifyDataSetChanged();
    }

    private void titleBar() {
        mTextView =(TextView)findViewById(R.id.top_title_info);
        mTextView.setText("领料列表");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setVisibility(View.VISIBLE);
        mButton.setText("查询");
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog();
            }
        });

        /*mRelativeLayout =(RelativeLayout) findViewById(R.id.sfc_gdlk_foottoliuzhuan);
        mRelativeLayout.setVisibility(View.VISIBLE);*/
    }

    private void showAlertDialog() {
        LayoutInflater inflater = this.getLayoutInflater();
        final View layout = inflater.inflate(R.layout.whm_gdll_seach, (ViewGroup) findViewById(R.id.whm_gdll_seach_layout));
        final Dialog alertDialog= new AlertDialog.Builder(this).setCancelable(false).setView(layout).create();
        final TextView mTextView =(TextView)layout.findViewById(R.id.top_title_info);
        mTextView.setText("查询条件");
        final Button back = (Button) layout.findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                alertDialog.hide();
            }
        });
        //仓库类型
        final Button  mButtonCK =(Button)layout.findViewById(R.id.whm_gdll_seach_ck_sm);
        mButtonCK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(GdllActivity.this, GdlkCkActivity.class);
                startActivityForResult(intent, 0x0001);
            }
        });
        mEditTextCK=(EditText)layout.findViewById(R.id.whm_gdll_seach_ck);
        String wareh = PreferenceManager.getDefaultSharedPreferences(this).getString(WAREH,null);
        if(wareh!=null){
            mEditTextCK.setText(String.valueOf(wareh));
        }
        final Calendar c = Calendar.getInstance();
        //开始时间
        mEditTextBeginDate=(EditText)layout.findViewById(R.id.whm_gdll_seach_date_b);
        c.add(Calendar.DATE,-2);
        mEditTextBeginDate.setText(String.format("%d-%02d-%02d", c.get(Calendar.YEAR),c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH)));
        mEditTextBeginDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               new DatePickerDialog(GdllActivity.this, 0, new DatePickerDialog.OnDateSetListener() {
                   @Override
                   public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth) {
                       String textString = String.format("%d-%02d-%02d", startYear,startMonthOfYear + 1, startDayOfMonth);
                       mEditTextBeginDate.setText(textString);
                   }
               }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), true).show();
            }
        });
        //结束时间
        mEditTextEndDate=(EditText)layout.findViewById(R.id.whm_gdll_seach_date_e);
        c.add(Calendar.DATE,4);
        mEditTextEndDate.setText(String.format("%d-%02d-%02d", c.get(Calendar.YEAR),c.get(Calendar.MONTH)+1, c.get(Calendar.DAY_OF_MONTH)));
        mEditTextEndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(GdllActivity.this, 0, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth) {
                        String textString = String.format("%d-%02d-%02d", startYear,startMonthOfYear + 1, startDayOfMonth);
                        mEditTextEndDate.setText(textString);
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), true).show();
            }
        });
        //工单号
        mEditTextMannos = (EditText)layout.findViewById(R.id.whm_gdll_seach_manno);
        final Button mButtonManno=(Button)layout.findViewById(R.id.whm_gdll_seach_manno_sm);
        mButtonManno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(GdllActivity.this, CaptureActivity.class), 0x0003);
            }
        });

        //申请人
        mEditTextUser = (EditText)layout.findViewById(R.id.whm_gdll_seach_user);
        final Button mButtonUser=(Button)layout.findViewById(R.id.whm_gdll_seach_user_select);
        mButtonUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(GdllActivity.this, GdllUserActivity.class);
                startActivityForResult(intent, 0x0002);
            }
        });
        //确定
        final Button mButtonSubmit=(Button)layout.findViewById(R.id.whm_gdll_seach_submit);
        mButtonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long diff = 0;
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    Date d1 = df.parse(mEditTextBeginDate.getText().toString());
                    Date d2= df.parse(mEditTextEndDate.getText().toString());
                    diff = (d2.getTime() - d1.getTime())/(24*60*60*1000);
                }catch (Exception e)
                {
                }
                if (mEditTextCK.getText().toString().isEmpty()) {
                    AppUtils.showTip(GdllActivity.this, "仓库不能为空");
                }else if (mEditTextBeginDate.getText().toString().isEmpty()) {
                    AppUtils.showTip(GdllActivity.this, "开始日期不能为空");
                }else if (mEditTextEndDate.getText().toString().isEmpty()) {
                    AppUtils.showTip(GdllActivity.this, "结束日期不能为空");
                }else if (diff < 0) {
                    AppUtils.showTip(GdllActivity.this, "结束日期不能小于开始日期");
                }else if (diff>5) {
                    AppUtils.showTip(GdllActivity.this, "日期范围最大支持5天");
                }else {
                    mSalaryDatas.clear();
                    AsyncLoader task = new AsyncLoader();
                    task.execute("302"
                                 , mEditTextCK.getText().toString()
                                 , mEditTextBeginDate.getText().toString()
                                 , mEditTextEndDate.getText().toString()
                                 , mEditTextUser.getText().toString()
                                 , mEditTextMannos.getText().toString()
                    );
                    alertDialog.hide();
                }
            }
        });
        alertDialog.show();
    }
    public class AsyncLoader extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showdialog.showDialog(GdllActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Wareh", params[1]);
                param.put("BeginDate", params[2]);
                param.put("EndDate", params[3]);
                param.put("AppUser", params[4]);
                param.put("Mannos", params[5]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            ManpahdTLabBean commonBean = new Gson().fromJson(s, ManpahdTLabBean.class);
            if (commonBean.getCode() < 1) {
                AppUtils.showTip(GdllActivity.this, commonBean.getMsg());
            } else {
                manpahdTBeans = commonBean.getResult();
                startProssThread();
            }
            showdialog.closeDialog();
        }
    }
    private void getData(int PageNo){
        if(manpahdTBeans==null) return;
        int count = (intPageNo*pageCount)> manpahdTBeans.size()?manpahdTBeans.size():intPageNo*pageCount;
        for(int i = (intPageNo-1)* pageCount;i< count;i++){
            mSalaryDatas.add(manpahdTBeans.get(i));
        }
    }
    private void  showList(){
        // 获取更多数据之外的请求，如首次请求数据，
        if (!isPressMore) {
            getData(intPageNo);
            adapter = new SalaryAdapter(GdllActivity.this);
            prossinfo_lv.setAdapter(adapter);
        }else {
            // 获取更多数据
            getData(intPageNo);
            adapter.notifyDataSetChanged();
        }
        // 判断是否有下一页
        if (manpahdTBeans.size() > mSalaryDatas.size()) {
            // 显示并启用自动获取更多
            mPullDownView.setShowFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(true, 1);
        } else {
            // 隐藏 并禁用尾部
            mPullDownView.setHideFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(false, 1);
        }
        // 告诉它获取更多完毕 这个事线程安全的 可看源代码
        mPullDownView.notifyDidMore();

        isPressMore = false;
    }
    /**
     * listview单项点击事件
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectedIndex = position-1;
        Bundle bundle = new Bundle();
        bundle.putSerializable("gdllDetail", (ManpahdTLabBean.ManpahdTBean) (manpahdTBeans.get(position - 1)));
        Intent intent = new Intent();
        intent.setClass(GdllActivity.this, GdllLlActivity.class);
        intent.putExtras(bundle);
        startActivityForResult(intent, 0x0004);
    }

    /**
     * listview刷新
     */
    public void onRefresh() {

    }
    /**
     * listview更多
     */
    public void onMore() {
        isPressMore = true;
        // 发送更多请求
        intPageNo++;
        startProssThread();
    }
    // 启动线程
    private void startProssThread() {
        showList();
    }
    public class SalaryAdapter extends BaseAdapter {
        private LayoutInflater inflater = null;
        public SalaryAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mSalaryDatas.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            holder = new ViewHolder();
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_VERTICAL;
            convertView = inflater.inflate(R.layout.whm_gdll_list, null);
            holder.gdll_list_itnbr = (TextView) convertView.findViewById(R.id.whm_gdll_list_itnbr);
            holder.gdll_list_appnum = (TextView) convertView.findViewById(R.id.whm_gdll_list_appnum);
            holder.gdll_list_onhand1 = (TextView) convertView.findViewById(R.id.whm_gdll_list_onhand1);
            holder.gdll_list_appuser = (TextView) convertView.findViewById(R.id.whm_gdll_list_user);
            holder.gdll_list__detail = (ImageView) convertView.findViewById(R.id.whm_gdll_list_detail);
            holder.gdll_list_grp = (TextView) convertView.findViewById(R.id.whm_gdll_list_grp);
            holder.gdll_list_pisdate = (TextView) convertView.findViewById(R.id.whm_gdll_list_pidate);

            holder.gdll_list_itnbr.setText(mSalaryDatas.get(position).getItnbr());
            holder.gdll_list_appnum.setText(mSalaryDatas.get(position).getAppNum().toString());
            holder.gdll_list_onhand1.setText(mSalaryDatas.get(position).getOnhand1().toString());
            if(mSalaryDatas.get(position).getOnhand1()>0){
                holder.gdll_list_onhand1.setBackground(getResources().getDrawable(R.color.ui_new_btn_yes_normal_solid));
                ColorStateList csl = (ColorStateList) getResources().getColorStateList(R.color.white);
                holder.gdll_list_onhand1.setTextColor(csl);
            }
            else {
                holder.gdll_list_onhand1.setBackground(getResources().getDrawable(R.color.encode_view));
            }
            holder.gdll_list_appuser.setText(mSalaryDatas.get(position).getAppUserName());
            holder.gdll_list__detail.setImageResource(R.drawable.right);
            holder.gdll_list_grp.setText(mSalaryDatas.get(position).getGrpName());
            holder.gdll_list_pisdate.setText(mSalaryDatas.get(position).getPisDate());
            convertView.setTag(holder);
            return convertView;
        }

        class ViewHolder {
            TextView gdll_list_itnbr;
            TextView gdll_list_appnum;
            TextView gdll_list_onhand1;
            TextView gdll_list_appuser;
            ImageView gdll_list__detail;
            TextView gdll_list_grp;
            TextView gdll_list_pisdate;
        }
    }
}

